/* eslint-disable */
import React, { Component } from 'react';
import { IMAGE_DOMAIN } from '../../utils/common';
import { connect } from 'dva';

const placeholderImg = require("../../assets/img/loading.gif");
const noImg = require("../../assets/img/error.jpg");

class Img extends Component {
  // 构造
  constructor(props) {
    super(props);
    //  this.scrollEl = '';
    this.state = {
      isLoaded: false,
      wrapoffsetHeight: 0,
      didMount: false,
      //defaultImgSrc:"",
      // once:false
    };
    this.lazyImg = null;
    this.fathersNode = null;
    //使用函数节流，性能优先
    //this.handleScroll = this.throttle(this._handleScroll, 100);
  }

  componentDidMount() {
    //const fathers=document.getElementById('ScrollUseMy');
    const wrap = document.getElementById('wrapperScrollUseMy');
    //console.log(this.props.app.scroolHright);
    //const img = this.refs.lazyImg;
    //let ImgScrollTop = this.getPos(img, fathers);
    //console.log(wrap);
    if (wrap != null) {
      this.setState({
        wrapoffsetHeight: wrap.offsetHeight,
        ImgOffsetHeight: this.lazyImg.offsetHeight,
        didMount: true
      })

    }
    this.fathersNode = document.getElementById('ScrollUseMy');
    //this.scrollEl.addEventListener('scroll', this.handleScroll);
    // document.addEventListener('resize', this.handleScroll);
    //this._handleScroll();
  }

  getStyle = (obj, attr) => {
    if (obj.currentStyle) {
      return obj.currentStyle[attr];
    }
    else {
      return getComputedStyle(obj, false)[attr];
    }
  }

  getPos = (ele, fathers) => {
    let top = ele.offsetTop;
    //let left=ele.offsetLeft;
    let offsetEle = ele.offsetParent;
    while (offsetEle && offsetEle != fathers) {
      top += offsetEle.offsetTop;
      let bTOPWidth = 0;
      if (bTOPWidth = parseInt(this.getStyle(offsetEle, 'borderTopWidth'))) {
        top += bTOPWidth;
      }

      // left+=offsetEle.offsetLeft;
      // let bLeftWidth=0;
      // if( bLeftWidth=parseInt(getStyle(offsetEle,'borderLeftWidth'))){
      //     left+=bLeftWidth;
      // }
      offsetEle = offsetEle.offsetParent;
    }
    // let o={};
    // o.x=left;
    // o.y=top;
    return top;
  }

  /**
   * 移除事件
   */
  componentWillUnmount() {
    //console.log(11);
    //this.scrollEl.removeEventListener('scroll', this.handleScroll);
    //document.removeEventListener('resize', this.handleScroll);
    // console.log(timer);
  }

  getImgScrollTop = () => {
    if (this.state.didMount && this.lazyImg != null) {
      //const fathers=document.getElementById('ScrollUseMy');
      //const wrap=document.getElementById('wrapperScrollUseMy');
      //console.log(this.props.app.scroolHright);
      //const img = this.refs.lazyImg;
      const ImgScrollTop = this.getPos(this.lazyImg, this.fathersNode);
      return ImgScrollTop
    } else {
      return 0
    }

  }

  /**
   * 获取滚动条滚动的高度
   */
  getScrollTop = () => {
    let scrollTop = 0;
    // if (document.documentElement && document.documentElement.scrollTop) {
    //   scrollTop = document.documentElement.scrollTop;
    // } else if (document.body) {
    //   scrollTop = document.body.scrollTop;
    // } else {
    //   scrollTop = window.scrollY || window.pageYOffset;
    // }
    //console.log(document.getElementById(this.props.ElId).scrollTop);
    scrollTop = this.scrollEl.scrollTop;
    return scrollTop;
  }

  /**
   * 获取当前图片距离顶部的xy坐标
   */
  // getNodeTop=() => {
  //   const viewTop = this.getScrollTop();
  //
  //   const img = this.refs.lazyImg; //当前节点
  //  // console.log(img);
  //   if (img === undefined) {
  //     this.scrollEl.removeEventListener('scroll', this.handleScroll);
  //     this.scrollEl.removeEventListener('resize', this.handleScroll);
  //     return { isMount: false };
  //   }
  //   const nodeTop = img.getBoundingClientRect().top + viewTop;
  //   const nodeBottom = nodeTop + img.offsetHeight;
  //   return {
  //     nodeTop,
  //     nodeBottom,
  //   };
  // }

  /**
   * 获取窗口的高度
   * @returns {XML}
   */
  // getClientHeight=() => {
  //   let clientHeight = 0;
  //   if (document.body.clientHeight && document.documentElement.clientHeight) {
  //     clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
  //   } else {
  //     clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
  //   }
  //   return clientHeight;
  // }

  /**
   * 处理滚动事件
   * @returns {XML}
   */
  // _handleScroll = () => {
  //  // console.log(1);
  //   const { offset } = this.props; //偏移量
  //
  //   const viewTop = this.getScrollTop();
  //   const viewBottom = viewTop + this.getClientHeight();
  //
  //   const { nodeTop = viewBottom, nodeBottom = viewTop, isMount = true } = this.getNodeTop();
  //
  //  // console.log(this.Mount);
  //
  //   //当图片出现在视野范围内,设置真正的图片，同时移除监听
  //   if (nodeBottom + offset >= viewTop && nodeTop - offset <= viewBottom) {
  //     if (isMount == true) {
  //       this.setState({
  //         isLoaded: true,
  //       });
  //     }
  //     this.scrollEl.removeEventListener('scroll', this.handleScroll);
  //     this.scrollEl.removeEventListener('resize', this.handleScroll);
  //   }
  // }

  // _handleScroll = (isload, addedSrc, placeholderImg , true_src) => {
  //     //console.log(isload,addedSrc ,placeholderImg);
  //     true_src = isload ? addedSrc : placeholderImg;
  //     //console.log(true_src);
  //     return true_src;
  // }

  // throttle(fn, delay) {
  //   let timer = null;
  //  // console.log(timer);
  //   return function () {
  //     const context = this;
  //     const args = arguments;         // Use the rest parameters instead of 'arguments'
  //     clearTimeout(timer);
  //     timer = setTimeout(() => {
  //         fn.apply(context, args);
  //     }, delay);
  //   };
  // }

  render() {
    const {
      className,
      style,
      src,
      // ElId,
      app, offset, load = () => { }, ...othersProps } = this.props;
    //console.log(app)
    const { isLoaded, wrapoffsetHeight, ImgOffsetHeight } = this.state;
    let addedSrc = src.indexOf('http://wx') === 0 ? src : `${IMAGE_DOMAIN}${src}`;
    let ImgScrollTop = this.getImgScrollTop();
    let isload = Math.abs(app.targetScrollHeight) + wrapoffsetHeight + offset > ImgScrollTop && ImgScrollTop > Math.abs(app.targetScrollHeight) - offset;
    let true_src = isload ? addedSrc : noImg;
    //console.log(this.handleScroll(isload, addedSrc, placeholderImg, true_src));
    //console.log(app.targetScrollHeight,ImgScrollTop);
    //console.log(ImgScrollTop);
    return (
      <img
        //{ ...othersProps }
        ref={(n) => { this.lazyImg = n }}
        className={className}
        onLoad={() => {
          if (isload) {
            // console.log(1);
            this.setState({
              isLoaded: true,
            });
            load();
          }
        }}
        style={style}
        src={isLoaded == true ? addedSrc : true_src}
        onError={(e) => {
          e.target.src = require("../../assets/img/error.jpg");
        }}
      />
    );
  }
}


Img.defaultProps = {
  //placeholder: '../../assets/img/home.png', //默认图片
  offset: 200, //默认距离
  // ElId: 'ScrollUseMy',
};

export default connect(({ app }) => ({ app }))(Img);

/*
 * 图片懒加载，网络图片使用
 * */
